package controllers

import (
	"myapp/dal/model"
	"myapp/dal/query"
	"myapp/middleware"
	"myapp/validates"
	"net/http"
	"strconv"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"gorm.io/gorm"
)

func TrendListHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		//locale, _ := c.GetQuery("locale")

		pagestr, _ := c.GetQuery("page")
		page1, _ := strconv.Atoi(pagestr)
		if page1 <= 1 {
			page1 = 1
		}

		querys := query.Trend.Where()

		offset := (page1 - 1) * 5
		needs, _, _ := querys.Order(query.Trend.ID.Desc()).FindByPage(offset, 5)

		userId, _ := c.Get("userID")
		user_id := 0
		if v, ok := userId.(uint); ok {
			user_id = int(v)
		}

		// 将查询结果转换为自定义结构体
		var customNeeds []validates.Trend
		for _, need := range needs {
			customNeeds = append(customNeeds, validates.ProcessTrend(need, user_id))
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"needs": customNeeds,
		}})
	}
}

func TrendViewHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		id, _ := strconv.Atoi(c.Param("id"))

		needs, _ := query.Trend.Where(query.Trend.ID.Eq(int32(id))).Take()

		userId, _ := c.Get("userID")
		user_id := 0
		if v, ok := userId.(uint); ok {
			user_id = int(v)
		}

		pagestr, _ := c.GetQuery("page")
		page1, _ := strconv.Atoi(pagestr)
		if page1 <= 1 {
			page1 = 1
		}

		querys := query.Comment.Where(query.Comment.TrendID.Eq(needs.ID))

		offset := (page1 - 1) * 5
		comments, _, _ := querys.Order(query.Comment.ID.Desc()).FindByPage(offset, 5)

		// 将查询结果转换为自定义结构体
		var customComments []validates.Comment
		for _, comment := range comments {
			customComments = append(customComments, validates.ProcessComment(comment, user_id))
		}

		c.JSON(http.StatusOK, gin.H{"code": 0, "data": gin.H{
			"needs":    validates.ProcessTrend(needs, user_id),
			"comments": customComments,
		}})
	}
}

func PostHandler(db *gorm.DB) gin.HandlerFunc {
	return func(c *gin.Context) {
		query.SetDefault(db)

		var dto validates.Trend
		if err := c.ShouldBindJSON(&dto); err != nil {
			errs, ok := err.(validator.ValidationErrors)
			if !ok {
				// 非validator.ValidationErrors类型错误直接返回
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  err.Error(),
				})
				return
			}
			// validator.ValidationErrors类型错误则进行翻译
			c.JSON(http.StatusOK, gin.H{
				"code": 1,
				"msg":  middleware.GetFirstErrorMessage(errs),
			})
			return
		}

		userId, _ := c.Get("userID")
		if v, ok := userId.(uint); ok {
			user, _ := query.User.Where(query.User.ID.Eq(int32(v))).Take()
			if user.IsProfile == 0 {
				c.JSON(http.StatusOK, gin.H{
					"code": 110,
					"msg":  "对不起，请将个人资料补充完整再提交",
				})
				return
			}

			now := time.Now()
			twentyFourHoursAgo := now.Add(-1 * time.Minute)

			count, _ := query.Trend.Where(query.Trend.UserID.Eq(int32(v)), query.Trend.CreatedAt.Gte(twentyFourHoursAgo)).Count()
			if count >= 1 {
				c.JSON(http.StatusOK, gin.H{
					"code": 1,
					"msg":  "对不起，您发布得太密集，请过1分钟再发",
				})
				return
			}

			images := strings.Join(dto.Images, ",")
			nd := model.Trend{
				Content: dto.Content,
				Images:  images,
			}

			nd.UserID = int32(v)

			query.Trend.Create(&nd)

			c.JSON(http.StatusOK, gin.H{"code": 0, "data": nd.ID})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"code": 1,
			"msg":  "程序异常",
		})
	}
}
